package com.uchedao.vehicledetection.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.uchedao.mybaselibrary.utils.JsonUtils;
import com.uchedao.mybaselibrary.utils.LogUtil;
import com.uchedao.mybaselibrary.view.dialog_for_ios.ZAlertDialog;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.adapter.InspectedCarSourceAdapter;
import com.uchedao.vehicledetection.config.Api;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.inf.InspectedCarSourceSubmit;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.InspectedCarSourceEntity;
import com.uchedao.vehicledetection.model.Photo;
import com.uchedao.vehicledetection.model.PublishModel;
import com.uchedao.vehicledetection.model.PublishPhotoModel;
import com.uchedao.vehicledetection.model.response.CheckedCarListResponse;
import com.uchedao.vehicledetection.network.HttpRequest;
import com.uchedao.vehicledetection.utils.ProgressDialogUtil;
import com.uchedao.vehicledetection.utils.ViewUtil;
import com.uchedao.vehicledetection.view.widget.pulltorefresh.library.PullToRefreshBase;
import com.uchedao.vehicledetection.view.widget.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 已验车源
 */
public class InspectedCarSourceActivity extends CJDBaseActivity {

    private TextView tvNoData;
    private PullToRefreshListView lvSource;

    private int pageNo;
    private int pageSize;
    private InspectedCarSourceAdapter adapter;

    private PublishModel publishModel;
    private EditText et_floor;
    private AlertDialog _dialog;
    private ProgressDialog dialog;


    @Override
    protected String getActivityTag() {
        return "InspectedCarSourceActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_inspected_car_source;
    }

    @Override
    protected void initView() {
        tvNoData = (TextView) findViewById(R.id.tvNoData);
        lvSource = (PullToRefreshListView) findViewById(R.id.lvInspectedCarSource);
    }

    @Override
    protected void initData() {
        setTitle("已验车源");

        lvSource.setMode(PullToRefreshBase.Mode.BOTH);
        pageNo = 0;
        pageSize = 15;
        getSourceList(pageNo, pageSize);
    }

    @Override
    protected void initListener() {
        lvSource.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                pageNo = 0;
                getSourceList(pageNo, pageSize);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                getSourceList(pageNo, pageSize);
            }
        });
    }

    /**
     * 获取车源列表
     */
    public void getSourceList(int pageNo, int pageSize) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("offset", pageNo * pageSize + "");
        params.put("limit", pageSize + "");
        Request req = HttpRequest.getRequest(HttpRequest.GET, Api.Action.CHECKED_CAR, params,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        lvSource.onRefreshComplete();
                        CheckedCarListResponse entity = new Gson().fromJson(response, CheckedCarListResponse.class);
                        updateView(entity.getList());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        lvSource.onRefreshComplete();
                        LogUtil.e(error.getMessage());
                    }
                });
        addQueue(req);
    }

    public void updateView(List<InspectedCarSourceEntity> list) {
        if (list != null && list.size() > 0)
            tvNoData.setVisibility(View.GONE);

        if (pageNo == 0 || adapter == null) {
            adapter = new InspectedCarSourceAdapter(this, list, sourceSubmit);
            lvSource.setAdapter(adapter);
        }
        if (pageNo > 0) {
            adapter.getmData().addAll(list);
            adapter.notifyDataSetChanged();
        }
        pageNo++;
    }


    /**
     * 提交开拍
     */
    InspectedCarSourceSubmit sourceSubmit = new InspectedCarSourceSubmit() {
        @Override
        public void showError(String error) {
            LogUtil.e("showError sourceSubmit");
            new ZAlertDialog.Builder(InspectedCarSourceActivity.this)
                    .setTitle("提示")
                    .setMessage(error)
                    .setNegativeButton("知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).show();
        }

        @Override
        public void submit(Draft draft) {
            LogUtil.e("submit 提交开拍");
            // TODO 提交开拍
            publishModel = convertDraftToPublishModel(draft);
            if (publishModel == null) {//检测信息已被删除或非本机数据
                LogUtil.e("publishModel == null showError sourceSubmit");
                showError(String.format("%s检测信息已被删除或非本机数据！"
                        , (TextUtils.isEmpty(draft.car_plate) ? "" : draft.car_plate)));
            } else {
                LogUtil.e("publishModel != null editFloorPrice sourceSubmit");
                if (TextUtils.isEmpty(publishModel.getFloor_price())) {
                    LogUtil.e("publishModel != null editFloorPrice sourceSubmit");
                    editFloorPrice();
                } else {
                    LogUtil.e("publishModel != null requestPublishCar sourceSubmit");
                    requestPublishCar(publishModel);
                }
            }
        }
    };

    private void editFloorPrice() {
        View custom = LayoutInflater.from(InspectedCarSourceActivity.this).inflate(R.layout.custom_dialog_floor, null, false);
        et_floor = (EditText) custom.findViewById(R.id.et_floor);
        custom.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _dialog.dismiss();
            }
        });
        custom.findViewById(R.id.btn_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String floor = et_floor.getText().toString();
                if (TextUtils.isEmpty(floor)) {
                    ViewUtil.showEditError(et_floor, getString(R.string.no_empty));
                    return;
                }
                publishModel.setFloor_price(floor);
                requestPublishCar(publishModel);
                _dialog.dismiss();
            }
        });
        _dialog = new ZAlertDialog
                .Builder(InspectedCarSourceActivity.this)
                .setTitle("设置")
                .setShowClose(true)
                .setView(custom).create();
        _dialog.show();
    }

    /**
     * 发拍车源
     */
    private void requestPublishCar(PublishModel publishModel) {
        ProgressDialogUtil.showProgressDlg(this, "正在努力的联系服务器……");
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", publishModel.getId());
        map.put("vin", publishModel.getVin());
        map.put("brand_id", publishModel.getBrand_id() + "");
        map.put("series_id", publishModel.getSeries_id() + "");
        map.put("model_id", publishModel.getModel_id() + "");
        map.put("car_number", publishModel.getCar_number());
        map.put("card_time", publishModel.getCard_time());
        map.put("kilometer", publishModel.getKilometer());
        map.put("floor_price", publishModel.getFloor_price());
        map.put("car_color", publishModel.getCar_color());
        map.put("year_check_time", publishModel.getYear_check_time());
        map.put("safe_force_time", publishModel.getSafe_force_time());
        map.put("safe_business_time", publishModel.getSafe_business_time());
        map.put("use_type", publishModel.getUse_type());
        map.put("transfer_num", publishModel.getTransfer_num());
        map.put("province", publishModel.getProvince());
        map.put("city", publishModel.getCity());
        map.put("plate_province", publishModel.getPlate_province());
        map.put("plate_city", publishModel.getPlate_city());
        map.put("note", publishModel.getNote());

        map.put("photos_list", JsonUtils.toJson(publishModel.getPhotos_list()));
        Request request = HttpRequest.getRequest(HttpRequest.POST, Api.Action.CAR_PUBLISH, map
                , new Response.Listener<JsonObject>() {
            @Override
            public void onResponse(JsonObject response) {
                ProgressDialogUtil.dismissProgressDlg();
                DbHelper dbHelper = new DbHelper(InspectedCarSourceActivity.this);
                dbHelper.deleteDraf(InspectedCarSourceActivity.this.publishModel.getCar_number());
                Toast.makeText(InspectedCarSourceActivity.this, "发布车源成功！", Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ProgressDialogUtil.dismissProgressDlg();
                Toast.makeText(InspectedCarSourceActivity.this, error.getMessage() + "", Toast.LENGTH_SHORT).show();
            }
        });
        addQueue(request);
    }

    /**
     * 将草稿转换成发拍车源数据类型
     */
    public PublishModel convertDraftToPublishModel(Draft draft) {
        PublishModel model = null;
        if (draft != null) {
            model = new PublishModel();
            //车辆基础信息
            model.setId(draft.info_number);
            model.setCar_number(draft.car_plate);
            model.setVin(draft.car_vin);
            //车辆型号信息
            model.setSeries_id(draft.base_info.use_info.series_id);
            model.setBrand_id(draft.base_info.use_info.brand_id);
            model.setModel_id(draft.base_info.use_info.model_id);
            // TODO 上牌时间(暂时使用初登日期)
            model.setCard_time(draft.base_info.use_info.card_time);
            // 公里数
            model.setKilometer(draft.base_info.car_type_info.kilometer);
            // TODO 保留价
            model.setFloor_price(draft.base_info.process_info.save_price);
            // 年检、商业、交强
            model.setYear_check_time(draft.base_info.process_info.year_check_time);
            model.setSafe_force_time(draft.base_info.process_info.safe_force_time);
            model.setSafe_business_time(draft.base_info.process_info.safe_business_time);

            model.setCar_color(draft.base_info.use_info.color);
            model.setUse_type(draft.base_info.use_info.use_quality);
            model.setTransfer_num(draft.base_info.transfer_info.transfer_num);
            model.setProvince(draft.base_info.use_info.province);
            model.setCity(draft.base_info.use_info.city);
            // TODO 车牌所在地（暂时使用车辆注册地）
            model.setPlate_province(draft.base_info.use_info.province);
            model.setPlate_city(draft.base_info.use_info.city);
            // TODO 车况说明（暂时使用车检说明）
            model.setNote(draft.condition.note);
            // TODO 车辆图片
            ArrayList<PublishPhotoModel> photos_list = new ArrayList<PublishPhotoModel>();
            for (int i = 0; i < draft.photo.length; i++) {
                Photo photo = draft.photo[i];
                if (photo != null && !TextUtils.isEmpty(photo.pic_url)) {
                    PublishPhotoModel photoModel = new PublishPhotoModel();
                    switch (i) {
                        case 0://行驶证
                            photoModel.setObject_type(3);
                            break;
                        case 1:
                        case 2://身份证图片
                            photoModel.setObject_type(2);
                            break;
                        default://其他
                            photoModel.setObject_type(1);
                            break;
                    }
                    photoModel.setNote(photo.name);
                    photoModel.setFile_path(photo.pic_url);
                    photos_list.add(photoModel);
                }
            }
            model.setPhotos_list(photos_list);
        }
        return model;
    }
}
